package com.wechat.admin.aop;

import com.wechat.admin.annoation.AuthCheck;
import com.wechat.admin.exception.BusinessException;
import com.wechat.admin.exception.ErrorCode;
import com.wechat.admin.model.enums.UserRoleEnum;
import com.wechat.admin.model.vo.UserLoginInfoVo;
import com.wechat.admin.service.UserService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @Author:sjb
 * @CreateTime:2024-12-10
 * @Description: 权限校验AOP
 * @Version：1.0
 */
@Component
@Aspect
public class AuthCheckInterceptor {

    @Resource
    public UserService userService;

    @Around("@annotation(authCheck)")
    public Object authCheck(ProceedingJoinPoint proceedingJoinPoint, AuthCheck authCheck) throws Throwable {
        String role = authCheck.mustRole();

        UserLoginInfoVo currentLoginUser = userService.getCurrentLoginUser();
        String userRole = currentLoginUser.getUserRole();

        UserRoleEnum enumByValue = UserRoleEnum.getEnumByValue(role);
        if (enumByValue == null){
            return proceedingJoinPoint.proceed();
        }

        UserRoleEnum userRoleEnum = UserRoleEnum.getEnumByValue(userRole);
        if (userRoleEnum == null){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR,"无权限");
        }

        // 必须为管理员的权限校验
        if (UserRoleEnum.ADMIN.equals(enumByValue) && !UserRoleEnum.ADMIN.equals(userRoleEnum)){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR,"无权限");
        }
        return proceedingJoinPoint.proceed();
    }
}
